package org.ourgrid.peer.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.common.internal.response.ReleaseResponseTO;
import org.ourgrid.common.statistics.beans.peer.Peer;
import org.ourgrid.common.statistics.control.PeerControl;
import org.ourgrid.peer.business.dao.PeerDAOFactory;
import org.ourgrid.peer.dao.DiscoveryServiceClientDAO;
import org.ourgrid.peer.request.NotifyRemoteWorkerProviderFailureRequestTO;

public class NotifyRemoteWorkerProviderFailureRequester implements RequesterIF<NotifyRemoteWorkerProviderFailureRequestTO> {
	
	public List<IResponseTO> execute(NotifyRemoteWorkerProviderFailureRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		markProviderAsDown(request.getRwpAddress(), request.getRwpUserAtServer(), responses);
		
		return responses;
	}

	public static void markProviderAsDown(
			String rwpServiceID, String rwpUserAtServer,
			List<IResponseTO> responses) {
		DiscoveryServiceClientDAO dao = PeerDAOFactory.getInstance().getDiscoveryServiceClientDAO();
		
		boolean removed = dao.removeRemoteWorkerProviderAddress(rwpServiceID);
		
		if (removed) {
			ReleaseResponseTO releaseTO = new ReleaseResponseTO();
			releaseTO.setStubAddress(rwpServiceID);
			
			responses.add(releaseTO);
			
			Peer peer = PeerControl.getInstance().getPeerByCommuneAddress(responses, rwpUserAtServer);
			
			if (peer != null) {
				PeerControl.getInstance().peerIsDown(responses, peer.getDNdata());
			}
		}
	}
	
}
